/*
 * Copyright (c) 2008, Yifu Huang
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of SleekIce nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.sleekice.gui;

import com.sleekice.core.Renderable;
import com.sleekice.core.SleekCore;
import com.sleekice.core.Updatable;
import com.sleekice.input.Clickable;
import com.sleekice.input.Hoverable;
import com.sleekice.input.KeyboardInput;
import com.sleekice.input.MouseInput;
import com.sleekice.util.List;
import com.sleekice.util.ListNode;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;

public class GuiHandler implements Renderable, Updatable {

    private List<Widget> widgets_;
    private MouseInput mInput_;
    private KeyboardInput kInput_;
    private Keyable focusedObject_;
    
    /* an alias of the sleek core is only kept for aborting messages for now */
    private SleekCore sleekcore_;

    public GuiHandler(SleekCore sleekcore, KeyboardInput kInput, MouseInput mInput) {
        widgets_ = new List<Widget>();
        sleekcore_ = sleekcore;
        kInput_ = kInput;
        mInput_ = mInput;
    }

    public void addWidget(Widget widget) {
        widgets_.add(widget);

        /**
         * Adds this widget to the mouse input. Should limit the use of
         * instanceof. Possibly code a method that returns subwidgets from
         * that widget.
         */
        if (widget instanceof Hoverable) {
            mInput_.addTrigger((Hoverable) widget);
        }
        else if (widget instanceof ScrollBar) {
            ScrollBar temp = (ScrollBar) widget;
            mInput_.addTrigger(temp.getTopButton());
            mInput_.addTrigger(temp.getBottomButton());
        }
        else if (widget instanceof MessageDialog) {
            MessageDialog temp = (MessageDialog) widget;
            mInput_.addTrigger(temp.getOkButton());
            temp.setGuiHandler(this);
        }
    }
    
    public void disableAll() {
        ListNode<Widget> widgetNode = widgets_.getFirst();
        while (widgetNode != null) {
            widgetNode.getValue().setEnabled(false);
            widgetNode = widgetNode.next();
        }
    }
    
    public void hideAll() {
        ListNode<Widget> widgetNode = widgets_.getFirst();
        while (widgetNode != null) {
            widgetNode.getValue().setVisible(false);
            widgetNode = widgetNode.next();
        }
    }
    
    public SleekCore getMain() {
        return sleekcore_;
    }
    
    public void removeWidget(Widget widget) {
        widgets_.delete(widget);
        if (widget instanceof Hoverable) {
            Hoverable temp = (Hoverable)widget;
            mInput_.removeTrigger(temp);
        }
    }

    public void render(Graphics2D g) {
        ListNode<Widget> widgetNode = widgets_.getFirst();
        while (widgetNode != null) {
            Widget widget = widgetNode.getValue();
            if (widget.isVisible()) {
                if (widget instanceof Renderable) {
                    Renderable temp = (Renderable) widget;
                    temp.render(g);
                }
            }
            widgetNode = widgetNode.next();
        }
    }

    public void update(double elapsedTime) {
        /* set focus to the appropriate widget */
        Clickable lastClicked = mInput_.getLastClicked();
        if (lastClicked != null) {
            if (lastClicked instanceof Keyable) {
                /**
                 * If the last clicked item is not the focused item before,
                 * deplete the released chars in keyboard input.
                 */
                if (focusedObject_ != null) {
                    if (!focusedObject_.equals(lastClicked)) {
                        while (kInput_.pollCharReleased() != null) {
                        }
                        while (kInput_.pollKeyPressed() != null) {
                        }
                        focusedObject_ = (Keyable) lastClicked;
                        focusedObject_.setFocused(true);
                    }
                }
                else {
                    while (kInput_.pollCharReleased() != null) {
                    }
                    while (kInput_.pollKeyPressed() != null) {
                    }
                    focusedObject_ = (Keyable) lastClicked;
                    focusedObject_.setFocused(true);
                }
            }
            else {
                if (focusedObject_ != null) {
                    focusedObject_.setFocused(false);
                }
                focusedObject_ = null;
            }
        }
        else {
            if (focusedObject_ != null) {
                focusedObject_.setFocused(false);
            }
            focusedObject_ = null;
        }

        /**
         * If there is a widget focused, take characters released from the
         * Keyboard Input.
         */
        if (focusedObject_ != null) {
            Character c;
            while ((c = kInput_.pollCharReleased()) != null) {
                focusedObject_.addChar(c.charValue());
            }

            Integer keyPressed;
            while ((keyPressed = kInput_.pollKeyPressed()) != null) {
                if (keyPressed.equals(KeyEvent.VK_BACK_SPACE)) {
                    focusedObject_.removeChar();
                }
            }
        }

        /* update all the widgets */
        ListNode<Widget> widgetNode = widgets_.getFirst();
        while (widgetNode != null) {
            Widget widget = widgetNode.getValue();
            if (widget.isEnabled()) {
                if (widgetNode.getValue() instanceof Updatable) {
                    Updatable temp =
                        (Updatable) widgetNode.getValue();
                    temp.update(elapsedTime);
                }
            }
            widgetNode = widgetNode.next();
        }
    }
}